package com.yuntongxun.ecdemo.ui.voip;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;

import com.yuntongxun.ecdemo.R;
import com.yuntongxun.ecdemo.common.utils.LogUtil;
import com.yuntongxun.ecdemo.common.utils.ToastUtil;
import com.yuntongxun.ecdemo.storage.ContactSqlManager;
import com.yuntongxun.ecdemo.ui.SDKCoreHelper;
import com.yuntongxun.ecdemo.ui.contact.ECContacts;
import com.yuntongxun.ecdemo.ui.voip.ECCallHeadUILayout.OnSendDTMFDelegate;
import com.yuntongxun.ecdemo.voicechat.bean.UserInfo;
import com.yuntongxun.ecdemo.voicechat.util.JsonHelper;
import com.yuntongxun.ecdemo.voicechat.view.MyImageSpan;
import com.yuntongxun.ecsdk.ECDevice;
import com.yuntongxun.ecsdk.ECError;
import com.yuntongxun.ecsdk.ECVoIPCallManager;
import com.yuntongxun.ecsdk.ECVoIPCallManager.CallType;
import com.yuntongxun.ecsdk.ECVoIPSetupManager;
import com.yuntongxun.ecsdk.SdkErrorCode;
import com.yuntongxun.ecsdk.VoIPCallUserInfo;

import java.io.IOException;
import java.io.InputStream;

/**
 * com.yuntongxun.ecdemo.ui.voip in ECDemo_Android
 * Created by Jorstin on 2015/7/3.
 */
public class VoIPCallActivity extends ECVoIPBaseActivity /*implements ECVoIPCallManager.OnCallProcessMultiDataListener*/{

    private static final String TAG = "ECSDK_Demo.VoIPCallActivity";
	private boolean isCallBack;

    MyImageSpan flagSpan;
    MyImageSpan genderSpan;

    @Override
    protected int getLayoutId() {
        return R.layout.ec_call_interface;
    }
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        initCall();
        isCreated=true;
        
    }

    private void initCall() {
        if(mIncomingCall) {
            // 来电
            mCallId = getIntent().getStringExtra(ECDevice.CALLID);
            LogUtil.e("mCallId----"+mCallId);
            mCallNumber = getIntent().getStringExtra(ECDevice.CALLER);
            LogUtil.e("mCallNumber----"+mCallNumber);
            ECContacts ecContacts= ContactSqlManager.getContact(mCallNumber);
            String info=ecContacts.getNickname();
            if (info.contains("(")){
                mCallName=info;
            }

        } else {
            // 呼出
            mCallName = getIntent().getStringExtra(EXTRA_CALL_NAME);
            mCallNumber = getIntent().getStringExtra(EXTRA_CALL_NUMBER);

            isCallBack = getIntent().getBooleanExtra(ACTION_CALLBACK_CALL, false);

        }

        initView();
        if (!mIncomingCall) {
            // 处理呼叫逻辑
            if (TextUtils.isEmpty(mCallNumber)) {
                ToastUtil.showMessage(R.string.ec_call_number_error);
                finish();
                return;
            }

            if (isCallBack) {
                VoIPCallHelper.makeCallBack(CallType.VOICE, mCallNumber);
            } else {
                //ECDevice.getECVoIPCallManager().setProcessDataEnabled(null , true , true , this);
                mCallId = VoIPCallHelper.makeCall(mCallType, mCallNumber);
                if (TextUtils.isEmpty(mCallId)) {
                    ToastUtil .showMessage(R.string.ec_app_err_disconnect_server_tip);
                    LogUtil.d(TAG, "Call fail, callId " + mCallId);
                    finish();
                    return;
                }
            }
            mCallHeaderView .setCallTextMsg(R.string.ec_voip_call_connecting_server);
        } else {
            mCallHeaderView.setCallTextMsg(" ");
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
    	if(!isCreated){
         super.onNewIntent(intent);
         initCall();
    	}
    }
    private boolean isCreated=false;

    private void initView() {
        mCallHeaderView = (ECCallHeadUILayout) findViewById(R.id.call_header_ll);
        mCallControlUIView = (ECCallControlUILayout) findViewById(R.id.call_control_ll);
        mCallControlUIView.setOnCallControlDelegate(this);


//        mCallHeaderView.getCallName().setText();
        setName(mCallName);
//        mCallHeaderView.getCallName().setCallName(mCallName);

        mCallHeaderView.setCallNumber(TextUtils.isEmpty(mPhoneNumber) ? mCallNumber : mPhoneNumber);
        mCallHeaderView.setCalling(false);

        ECCallControlUILayout.CallLayout callLayout = mIncomingCall ? ECCallControlUILayout.CallLayout.INCOMING
                : ECCallControlUILayout.CallLayout.OUTGOING;
        mCallControlUIView.setCallDirect(callLayout);

        mCallHeaderView.setSendDTMFDelegate(this);
    }


    @Override
    protected boolean isEnableSwipe() {
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isCreated=false;

    }

    /**
     * 连接到服务器
     * @param callId 通话的唯一标识
     */
    @Override
    public void onCallProceeding(String callId) {
        if(mCallHeaderView == null || !needNotify(callId)) {
            return ;
        }
        LogUtil.d(TAG, "onUICallProceeding:: call id " + callId);
        mCallHeaderView.setCallTextMsg(R.string.ec_voip_call_connect);
    }

    /**
     * 连接到对端用户，播放铃音
     * @param callId 通话的唯一标识
     */
    @Override
    public void onCallAlerting(String callId) {
        if(!needNotify(callId) || mCallHeaderView == null) {
            return ;
        }
        LogUtil.d(TAG , "onUICallAlerting:: call id " + callId);
        mCallHeaderView.setCallTextMsg(R.string.ec_voip_calling_wait);
        mCallControlUIView.setCallDirect(ECCallControlUILayout.CallLayout.ALERTING);
    }

    public UserInfo parseResult(String result) {
        JsonHelper<UserInfo> dataParser = new JsonHelper<UserInfo>(
                UserInfo.class);
        return dataParser.getData(
                result, "result");
    }

    private void setName(String info){
        if (info.contains("(")) {
            int index = info.indexOf("(");
            String message = info.substring(index + 1, info.length() - 1);
            UserInfo infos = null;
            try {
                infos = parseResult(message);
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (infos != null) {
                mCallHeaderView.getCallName().setText(infos.getNickName());
                String name = infos.getNickName() + "  ";
                String age = "  " + infos.getAge() + "  ";
                String nativel = " ";
                String learn = " ";
                if (infos.getNativeLanguage() != null) {
                    nativel = "  " + infos.getLearningLanguage() + "  ";
                }
                if (infos.getLearningLanguage() != null) {
                    learn = "  " + infos.getLearningLanguage() + "";
                }
//
//
                if (infos.getGender().equals("男")) {
                    genderSpan = new MyImageSpan(this, R.drawable.ic_man);
                } else {
                    genderSpan = new MyImageSpan(this, R.drawable.ic_woman);
                }

                MyImageSpan nativeSpan = new MyImageSpan(this, R.drawable.ic_speak);
                MyImageSpan learnSpan = new MyImageSpan(this, R.drawable.ic_learn);

                try {
                    InputStream is = this.getAssets().open("flag/" + infos.getCountry() + ".png");
                    flagSpan = new MyImageSpan(this, BitmapFactory.decodeStream(is));
                    is.close();
                } catch (IOException e) {
                    Log.e("----", e.toString());
                }

                mCallHeaderView.getCallName().setText("");
                //姓名
                SpannableString nameShow = new SpannableString(name);
                ForegroundColorSpan blackSpan = new ForegroundColorSpan(Color.WHITE);
                nameShow.setSpan(blackSpan, 0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                mCallHeaderView.getCallName().append(nameShow);

                //插入性别图标
                SpannableString showString = new SpannableString("1");
                showString.setSpan(genderSpan, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                mCallHeaderView.getCallName().append(showString);

                //年龄颜色
                SpannableString ageShow = new SpannableString(age);
                ForegroundColorSpan yellowSpan = new ForegroundColorSpan(this.getResources().getColor(R.color.voice_yellow));
                ageShow.setSpan(yellowSpan, 0, age.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                mCallHeaderView.getCallName().append(ageShow);

                //插入国旗图标
                showString.setSpan(flagSpan, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                mCallHeaderView.getCallName().append(showString);

                mCallHeaderView.getCallName().append("  ");

//                //插入本地语言的图标
//                showString.setSpan(nativeSpan, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//                mCallHeaderView.getCallName().append(showString);
//
//                //本地语言颜色
//                SpannableString nativeShow = new SpannableString(nativel);
//                ForegroundColorSpan greenSpan = new ForegroundColorSpan(this.getResources().getColor(R.color.voice_green));
//                nativeShow.setSpan(greenSpan, 0, nativel.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//                mCallHeaderView.getCallName().append(nativeShow);
//
//                //插入学习的图标
//                showString.setSpan(learnSpan, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//                mCallHeaderView.getCallName().append(showString);
//
//                //学习语言颜色
//                SpannableString learnShow = new SpannableString(learn);
//                ForegroundColorSpan greenSpan1 = new ForegroundColorSpan(this.getResources().getColor(R.color.voice_green));
//                learnShow.setSpan(greenSpan1, 0, learn.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//                mCallHeaderView.getCallName().append(learnShow);
            }
        }
    }

    /**
     * 对端应答，通话计时开始
     * @param callId 通话的唯一标识
     */
    @Override
    public void onCallAnswered(final String callId) {
        if(!needNotify(callId)|| mCallHeaderView == null) {
            return ;
        }
        LogUtil.d(TAG , "onUICallAnswered:: call id " + callId);
        mCallHeaderView.setCalling(true);
        isConnect = true;


//         boolean p =  isVoicePermission();
//        Log.e("aaaaaaaaaaaaa","aa"+p);
        
        
    }
    public boolean isVoicePermission() {
        try {
            AudioRecord record = new AudioRecord(MediaRecorder.AudioSource.MIC, 22050, AudioFormat.CHANNEL_CONFIGURATION_MONO,
                    AudioFormat.ENCODING_PCM_16BIT, AudioRecord.getMinBufferSize(22050, AudioFormat.CHANNEL_CONFIGURATION_MONO,
                    AudioFormat.ENCODING_PCM_16BIT));
            record.startRecording();
            int recordingState = record.getRecordingState();


            if (recordingState == AudioRecord.RECORDSTATE_STOPPED) {
                return false;
            }
            record.release();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public void onMakeCallFailed(String callId , int reason) {
        if(mCallHeaderView == null || !needNotify(callId)) {
            return ;
        }
        LogUtil.d(TAG, "onUIMakeCallFailed:: call id " + callId + " ,reason " + reason);
        mCallHeaderView.setCalling(false);
        isConnect = false;
        mCallHeaderView.setCallTextMsg(CallFailReason.getCallFailReason(reason));
        if(reason != SdkErrorCode.REMOTE_CALL_BUSY && reason != SdkErrorCode.REMOTE_CALL_DECLINED) {
            VoIPCallHelper.releaseCall(mCallId);
            finish();
        }
    }
    
    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	super.onResume();
    }

    /**
     * 通话结束，通话计时结束
     * @param callId 通话的唯一标识
     */
    @Override
    public void onCallReleased(String callId) {
        if(mCallHeaderView == null || !needNotify(callId)) {
            return ;
        }
        LogUtil.d(TAG , "onUICallReleased:: call id " + callId);
        mCallHeaderView.setCalling(false);
        isConnect = false;
        mCallHeaderView.setCallTextMsg(R.string.ec_voip_calling_finish);
        mCallControlUIView.setControlEnable(false);
        finish();
    }

	@Override
	public void onMakeCallback(ECError ecError, String caller, String called) {
		if(!TextUtils.isEmpty(mCallId)) {
			return ;
		}
		if(ecError.errorCode != SdkErrorCode.REQUEST_SUCCESS) {
			mCallHeaderView .setCallTextMsg("回拨呼叫失败[" + ecError.errorCode + "]");
		} else {
			mCallHeaderView .setCallTextMsg(R.string.ec_voip_call_back_success);
		}
		mCallHeaderView.setCalling(false);
        isConnect = false;
        mCallControlUIView.setControlEnable(false);
		finish();
	}

	@Override
	public void setDialerpadUI() {
		mCallHeaderView.controllerDiaNumUI();
	}

   /* @Override
    public byte[] onCallProcessData(byte[] inByte, boolean upLink) {

        ECLogger.d(TAG , "upLink audio %b " , upLink);
        return inByte;
    }

    @Override
    public byte[] onCallProcessVideoData(byte[] inByte, boolean upLink) {
        ECLogger.d(TAG , "upLink video %b " , upLink);
        return inByte;
    }*/
}
